import { createWebHistory, createRouter, RouterView as _RouterView } from 'vue-router';
import treeMap from '@/utils/tree-map';
import routes from '@/routes';

const views = import.meta.glob(['./{pages,layouts}/**/*.vue', '!./{pages,layouts}/**/_*.vue']);
const PAGE_NOT_FOUND = './pages/404.vue';

// console.log('views::', views);

const routeData = treeMap(routes, (node) => {
  if (!node.component) return { ...node, component: views[PAGE_NOT_FOUND] };
  const isLayout = (node.component || '').indexOf('layouts') === 0;
  const viewKey = isLayout ? node.component : `pages${node.component}`;

  // console.log("viewKey::", viewKey);
  const component = views[`./${viewKey}.vue`] || views[PAGE_NOT_FOUND];

  return { ...node, component };
});

const router = createRouter({
  history: createWebHistory(BASE_PATH),
  routes: routeData,
});

export const RouterView = _RouterView;

export default router;
